import { sourceUrl } from '@/config';
import { JOIN_KEY } from '@/dataTransfer/skuManager';
import closeImg from '@/images/common/close1.png';
import addImage from '@/images/common/add.png';
import subImage from '@/images/common/sub.png';
import { checkIsSold, getDefaultOptions } from '@/dataTransfer/product';
import utils from '@/utils/index';
import { Image, Text, View } from '@tarojs/components';
import Taro from '@tarojs/taro';
import classNames from 'classnames';
import React, { useCallback, useEffect, useRef, useState, useMemo } from 'react';
import { AtFloatLayout } from 'taro-ui';
import Icon from '@/components/Icon';
import { customeColor } from '@/src/config';
import './index.scss';

const SkuSelect = ({
  isOpened,
  product = {},
  handleClose,
  handlePurchaseNum,
  handleAddPro,
  dispatch,
}) => {
  const [skuCur, setSkuCur] = useState(null);
  const [skuInfo, setSkuInfo] = useState({});
  const [inCarIdx, setInCarIdx] = useState(-1);
  const skuCurStr = useRef('');

  // 处理规格可选择的路径
  const { stockPath, defaultSel } = useMemo(() => {
    if (!Object.keys(product).length) {
      return {};
    }

    return getDefaultOptions(product, {
      option: product?.carList?.[0]?.optionSelObj,
    });
  }, [product]);

  useEffect(() => {
    let options = [];
    if (Object.keys(product).length > 0) {
      if (product.carList && product.carList.length > 0) {
        let optionObj = product.carList[0].optionSelObj;
        for (let key in optionObj) {
          options.push({ name: key, value: optionObj[key] });
        }
      } else {
        options = [...(defaultSel?.length ? defaultSel : product.defaultOptionForSku)];
      }
      setSkuCur(options);
    }
  }, [product, defaultSel]);

  useEffect(() => {
    if (skuCur !== null && Object.keys(product).length > 0) {
      getOptionPrice();
    }
  }, [skuCur]);

  useEffect(() => {
    if (skuCur !== null && Object.keys(product).length > 0) {
      let list = skuCur.map((item) => item.value);
      skuCurStr.current = list.join('、');

      let findCarIdx = -1;
      if (product.carList.length > 0) {
        for (let i = 0; i < product.carList.length; i++) {
          let coptionObj = product.carList[i].optionSelObj;
          let isNotSame = false;
          for (let s = 0; s < skuCur.length; s++) {
            if (isNotSame == true) {
              break;
            }
            for (let key in coptionObj) {
              if (skuCur[s].name == key) {
                if (skuCur[s].value != coptionObj[key]) {
                  isNotSame = true;
                  break;
                }
              }
            }
          }
          if (isNotSame == false) {
            findCarIdx = i;
            break;
          }
        }
      }
      setInCarIdx(findCarIdx);
    }
  }, [skuCur, product.carNum]);

  const checkOptionIsStock = useCallback(
    ({ name, value }) => {
      if (!stockPath) {
        return false;
      }

      if (!skuCur?.length) {
        return;
      }

      // 覆盖规格值
      let isSame = false;
      const options = skuCur.map((v) => {
        if (v.name === name) {
          isSame = true;
          return {
            ...v,
            value,
            fullPath: `${name}${JOIN_KEY}${value}`,
          };
        }

        return v;
      });

      // 添加规格值
      if (!isSame) {
        options.push({ name, value, fullPath: `${name}${JOIN_KEY}${value}` });
      }

      const isStock = checkIsSold(stockPath, options);

      return isStock;
    },
    [stockPath, skuCur],
  );

  const getOptionPrice = () => {
    dispatch({
      type: 'productList/getOptionPrice',
      payload: {
        productReleaseId: product.id,
        options: skuCur,
        activityId: product.activityId,
        orgId: product.orgId,
      },
    }).then((data) => {
      let showOptions = skuCur.map((op) => op.value);
      data.showOptionsStr = showOptions.join('，');
      setSkuInfo(data);
    });
  };

  const handleOpSelect = (name, value) => {
    let curSelOptions = [...skuCur];
    for (let i = 0; i < curSelOptions.length; i++) {
      if (name === curSelOptions[i].name) {
        curSelOptions[i].value = value;
        break;
      }
    }
    setSkuCur(curSelOptions);
  };

  let optionsDom = [];
  if (isOpened) {
    const options = product.optionsObj;

    for (let key in options) {
      let opDomList = options[key].map((op, index) => {
        let active = false;
        if (skuCur) {
          for (let i = 0; i < skuCur.length; i++) {
            if (key === skuCur[i].name) {
              if (op === skuCur[i].value) {
                active = true;
              }
              break;
            }
          }
        }

        const unSelectable = checkOptionIsStock({ name: key, value: op });

        return (
          <View
            className={
              'spec-item ' +
              (unSelectable ? 'unSelectable ' : '') +
              (active ? 'customePageStyleBg20 customePageBorderStyle' : '')
            }
            key={key + '_' + op + index}
            onClick={() => {
              if (unSelectable) {
                return;
              }
              handleOpSelect(key, op);
            }}
          >
            <View
              className={classNames(
                'text',
                active && 'customePageStyle',
                unSelectable && 'unSelectable',
              )}
            >
              {op}
            </View>
          </View>
        );
      });
      optionsDom.push(
        <>
          <View className={classNames('label-spec')} key={key + '_option'}>
            {key}
          </View>
          <View className="spec-group-wrap">
            <View className="spec-group">{opDomList}</View>
          </View>
        </>,
      );
    }
  }

  return (
    <View className="takeOutGoodsSpecSelect" catchMove>
      <AtFloatLayout isOpened={isOpened} onClose={handleClose}>
        <View className="inner">
          <View className="goods-info">
            <View className="goods">
              <Image
                // mode="widthFix"
                className="goodsSmallImg"
                src={
                  skuInfo.imageUrl?.length > 0
                    ? skuInfo.imageUrl.indexOf('http') === 0
                      ? skuInfo.imageUrl
                      : sourceUrl + skuInfo.imageUrl
                    : product?.url
                    ? product?.url.indexOf('http') === 0
                      ? product?.url
                      : sourceUrl + product?.url
                    : ''
                }
              />
              <View className="detail">
                <View className="curOp txt28 title">{skuInfo?.title || product?.title}</View>

                <View className="curOp txt24 gray mt8">
                  {skuInfo.showOptionsStr?.length
                    ? '已选：' + skuInfo.showOptionsStr
                    : '请选择商品规格'}
                </View>

                <View className="priceLine">
                  <View className="price customePageStyle">
                    <Text className="unit">¥</Text>
                    <Text className="zNum">
                      {parseInt(skuInfo.price > 0 ? skuInfo.price : product.price ?? 0)}
                    </Text>
                    <Text className="zUnit">
                      {utils.getDotStr(skuInfo.price > 0 ? skuInfo.price : product.price ?? 0)}
                    </Text>
                    <Text
                      className={classNames(
                        'zMore',
                        (skuInfo.price > 0 || !product.isMutilSku) && 'hidden',
                      )}
                    >
                      起
                    </Text>
                    {skuInfo.type == 3 && <Text className="cost">{skuInfo.cost}</Text>}
                    {skuInfo.type == 3 && (
                      <View className="activityInfo customePageBorderStyle50">
                        <Icon name="icon_labe" size={18} color={customeColor} />
                        <Text className="discount">{skuInfo.discount}折</Text>
                        {skuInfo.activityLimit > 0 && (
                          <>
                            <Text className="diliver customePageBackgroundStyle"></Text>
                            <Text className="activityLimit">
                              {'限' + skuInfo.activityLimit + '件'}
                            </Text>
                          </>
                        )}
                      </View>
                    )}
                  </View>
                </View>
              </View>
            </View>
            <Image src={closeImg} className="close-icon" onClick={handleClose} />
          </View>

          <View className="line" />

          <View className={'sku-account ' + (Taro.$bottomHight ? 'mgh' : '')}>
            <View className="skuSettings">{optionsDom.length > 0 && optionsDom}</View>
          </View>

          <View className="bottom flex-column">
            {inCarIdx != -1 && Object.keys(product).length > 0 && product.carList.length > 0 ? (
              <View className="account">
                <Text className="left-text">购买数量</Text>
                <View className="number-sel">
                  <View
                    className="opBox flex-row-center-center"
                    onClick={() => handlePurchaseNum('sub', product.carList[inCarIdx])}
                  >
                    <Image mode="widthFix" className="sub" src={subImage} />
                  </View>
                  <View className="num">
                    <View className="value">{product.carList[inCarIdx].num}</View>
                  </View>
                  <View
                    className="opBox flex-row-center-center"
                    onClick={() => handlePurchaseNum('add', product.carList[inCarIdx])}
                  >
                    <Image mode="widthFix" className="add" src={addImage} />
                  </View>
                </View>
              </View>
            ) : (
              <View className="bottomCtx flex-row--center">
                <View
                  className="bottomOps flex-row-center-center customePageBackgroundStyle"
                  onClick={() => handleAddPro(product, skuInfo)}
                >
                  加入购物车
                </View>
              </View>
            )}
            {Taro.$bottomHight && <View className="bottomHt"></View>}
          </View>
        </View>
      </AtFloatLayout>
    </View>
  );
};
export default SkuSelect;
